package top.juntower.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.juntower.pojo.GameCollection;
import top.juntower.pojo.HistoryInformation;
import top.juntower.pojo.SmsParams;
import top.juntower.pojo.User;
import top.juntower.pojo.vo.UserVo;
import top.juntower.service.impl.UserServiceImpl;
import top.juntower.utils.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Api(tags = "用户信息")
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    QiniuUtil qiniuUtil;

    @Autowired
    private RedisUtils redisUti;

    @Autowired
    AliYunSmsUtils aliYunSmsUtils;

    @Value("${qiniu.domain}")
    private String fileDomain;


    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    //登录判断
    @ApiOperation(value = "用户登录",response = User.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userphone", value = "用户手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "userpwd", value = "用户密码", dataType = "String", required = true),
            @ApiImplicitParam(name = "uAdmin", value = "用户属性", dataType = "Integer", required = true),
    })
    @PostMapping("/loginuser")
    public JsonResult UserList(String userphone,String userpwd,Integer uAdmin){
        if (userphone == null || userpwd == null || uAdmin == null){
            JsonResult.error(JsonResult.NO);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("uPhone",userphone);
        map.put("uPwd",Md5Salt.md5PlusSalt(userpwd));
        map.put("uAdmin",uAdmin);
        User user = userService.loginJudge(map);
        if (user==null){
            return JsonResult.error("账号或密码错误!");
        }
        return JsonResult.ok(user);
    }
    //判断是否被注册
    @ApiOperation(value = "判断是否被注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uPhone", value = "用户手机号", dataType = "String", required = true)
    })
    @PostMapping("/isRegister")
    public JsonResult isRegister(String uPhone) {
        if (uPhone == null) {
            JsonResult.error(JsonResult.NO);
        }
        //判断用户是否已存在
        int i = userService.isRegister(uPhone);
        if (i == 1) {
            return JsonResult.error("该手机号已经被注册");
        }
        return JsonResult.ok("该手机号没有被注册");
    }

    //用户发送邮箱返回验证码
    @ApiOperation(value = "用户发送手机号返回验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uPhone", value = "用户邮箱", dataType = "String", required = true)
    })
    @PostMapping("/sendEmail")
    public JsonResult sendEmail(String uPhone){
        if (uPhone == null ){
            JsonResult.error(JsonResult.NO);
        }
        //判断用户是否已存在
        int i = userService.isRegister(uPhone);
        if (i == 1) {
            return JsonResult.error("该手机号已经被注册");
        }
        String randomCode = randomCode();
        try {
            new Thread(() -> {
                SmsParams smsParams = new SmsParams(uPhone,randomCode);
                aliYunSmsUtils.sendSms(smsParams);
            }).start();
        } catch (Exception e) {
            return JsonResult.error("发送失败");
        }
        redisUti.set(uPhone,randomCode,2*60);
        return JsonResult.ok("发送成功");
    }

    //用户注册
    @ApiOperation(value = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uname", value = "用户名称", dataType = "String", required = true),
            @ApiImplicitParam(name = "uphone", value = "用户手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "upwd", value = "用户密码", dataType = "String", required = true),
            @ApiImplicitParam(name = "code", value = "用户验证码", dataType = "String", required = true)
    })
    @PostMapping("/register")
    public JsonResult register(String uname,String uphone,String upwd,String code) {
        if (uname == null || uphone == null || upwd == null || code == null) {
            JsonResult.error(JsonResult.NO);
        }
        int i = userService.isRegister(uphone);
        if (i == 1) {
            return JsonResult.error("该手机号已经被注册");
        }
        if (redisUti.get(uphone) != null && redisUti.get(uphone).equals(code)) {
            Map<String, String> map = new HashMap<>();
            map.put("uname", uname);
            map.put("uphone", uphone);
            map.put("upwd", Md5Salt.md5PlusSalt(upwd));
            int register = userService.register(map);
            if (register > 0) {
                return JsonResult.ok("注册成功");
            }
            return JsonResult.error(JsonResult.INSERT_MISS);
        }else {
            return JsonResult.error("验证码或手机号不正确");
        }
    }

    //修改用户头像
    @CrossOrigin
    @ApiOperation(value = "修改用户头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "用户头像图片", dataType = "MultipartFile", required = true),
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true)
    })
    @PostMapping("/updateuserimg")
    public JsonResult updateuserimg(@RequestParam("file") MultipartFile file,Integer uId) {
        if (file.isEmpty()) {
            return JsonResult.error("请选择文件");
        }
        try {
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            //默认不指定key的状况下，以文件内容的hash值做为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + fileExtend;

            qiniuUtil.upload(fileInputStream,fileKey);

            String tupain=fileDomain+"/"+fileKey;
            //修改数据库图片
            Map<String, Object> map = new HashMap<>();
            map.put("uId",uId);
            map.put("uImg",tupain);
            int i = userService.updateuserimg(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("上传失败");
        }
        return JsonResult.ok("上传成功");
    }

    //查询简单用户信息
    @ApiOperation(value = "查询简单用户信息",response = User.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
    })
    @PostMapping("/simpleInformation")
    public JsonResult simpleInformation(Integer uId){
        if (uId == null){
            JsonResult.error(JsonResult.NO);
        }
        UserVo userVo = userService.simpleInformation(uId);
        if (userVo == null){
            return JsonResult.error(JsonResult.MISS);
        }else {
            return  JsonResult.ok(userVo);
        }
    }
    //修改用户名称
    @ApiOperation(value = "修改用户名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "uName", value = "用户名称", dataType = "String", required = true)
    })
    @PostMapping("/updateUserName")
    public JsonResult updateUserName(Integer uId,String uName) {
        if (uId == null || uName == null) {
            JsonResult.error(JsonResult.NO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("uId",uId);
        map.put("uName",uName);
        int i = userService.updateUserName(map);
        if (i>0){
            return JsonResult.ok("修改成功");
        }else {
            return  JsonResult.error("修改失败");
        }
    }
//    //用户收藏
//    @ApiOperation(value = "用户收藏")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
//            @ApiImplicitParam(name = "giId", value = "游戏Id", dataType = "Integer", required = true)
//    })
//    @PostMapping("/userCollection")
//    public JsonResult userCollection(Integer uId,Integer giId) {
//        if (uId == null || giId == null) {
//            JsonResult.error(JsonResult.NO);
//        }
//            return  JsonResult.error("修改失败");
//    }

    //用户收藏信息
    @ApiOperation(value = "用户收藏信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageNum", value = "分页页码", dataType = "Integer", required = true)
    })
    @PostMapping("/GameCollectionInformation")
    public JsonResult GameCollectionInformation(Integer uId,Integer pageNum) {
        if (uId == null || pageNum == null) {
            JsonResult.error(JsonResult.NO);
        }
        PageHelper.startPage(pageNum,8);
        List<GameCollection> gameCollections = userService.GameCollectionInformation(pageNum, 8, uId);
        PageInfo<GameCollection> pageInfo = new PageInfo<GameCollection>(gameCollections);
        if (pageInfo == null){
            return JsonResult.error(JsonResult.MISS);
        }
        return  JsonResult.ok(pageInfo);
    }

    //增加历史记录
    @ApiOperation(value = "增加历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "giId", value = "游戏Id", dataType = "Integer", required = true)
    })
    @PostMapping("/addHistory")
    public JsonResult addHistory(Integer uId,Integer giId) {
        if (uId == null || giId == null) {
            return JsonResult.error(JsonResult.NO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("uId",uId);
        map.put("hDatetime",new Date());
        map.put("giId",giId);
        int i = userService.addHistory(map);
        if (i>0){
            return JsonResult.ok("添加成功");
        }
        return  JsonResult.error("添加失败");
    }

    //删除历史记录
    @ApiOperation(value = "删除历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hId", value = "历史记录Id", dataType = "Integer", required = true),
    })
    @PostMapping("/deleteHistory")
    public JsonResult deleteHistory(Integer hId) {
        if (hId == null) {
            JsonResult.error(JsonResult.NO);
        }

        int i = userService.deleteHistory(hId);
        if (i>0){
            return JsonResult.ok("删除成功");
        }
        return  JsonResult.error("删除失败");
    }

    //删除用户全部历史记录
    @ApiOperation(value = "删除用户全部历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
    })
    @PostMapping("/deleteUserIdHistory")
    public JsonResult deleteUserIdHistory(Integer uId) {
        if (uId == null) {
            JsonResult.error(JsonResult.NO);
        }
        int i = userService.deleteUserIdHistory(uId);
        if (i>0){
            return JsonResult.ok("删除成功");
        }
        return  JsonResult.error("删除失败");
    }

    //批量删除历史记录
    @ApiOperation(value = "批量删除历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moreUserId", value = "历史记录Id", dataType = "String", required = true),
    })
    @PostMapping("/deleteMoreUserIdHistory")
    public JsonResult deleteHistory(String moreUserId) {
        if (moreUserId == null) {
            JsonResult.error(JsonResult.NO);
        }
        List<Integer> del_ids=new ArrayList<>();
        String[] str_ids=moreUserId.split(",");
        for (String str_id : str_ids) {
            del_ids.add(Integer.parseInt(str_id));
        }
        int i = userService.deleteMoreUserIdHistory(del_ids);
        if (i > 0){
            return  JsonResult.ok("删除成功");
        }else {
            return  JsonResult.error("删除失败");
        }
    }

    //历史记录
    @ApiOperation(value = "历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageNum", value = "分页页码", dataType = "Integer", required = true)
    })
    @PostMapping("/history")
    public JsonResult history(Integer uId,Integer pageNum) {
        if (uId == null || pageNum == null) {
            JsonResult.error(JsonResult.NO);
        }
        PageHelper.startPage(pageNum,20);
        List<HistoryInformation> history = userService.history(uId,pageNum,20);
        PageInfo<HistoryInformation> pageInfo = new PageInfo<HistoryInformation>(history);
        if (pageInfo == null){
            return  JsonResult.error(JsonResult.MISS);
        }
        return  JsonResult.ok(pageInfo);
    }



    //用户发送邮箱返回验证码
    @ApiOperation(value = "用户发送手机号返回验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uPhone", value = "用户邮箱", dataType = "String", required = true)
    })
    @PostMapping("/wansendEmail")
    public JsonResult wansendEmail(String uPhone){
        if (uPhone == null ){
            JsonResult.error(JsonResult.NO);
        }
        //判断用户是否已存在
        int i = userService.isRegister(uPhone);
        if (i == 1) {
            String randomCode = randomCode();
            try {
                new Thread(() -> {
                    SmsParams smsParams = new SmsParams(uPhone, randomCode);
                    aliYunSmsUtils.sendSms(smsParams);
                }).start();
            } catch (Exception e) {
                return JsonResult.error("发送失败");
            }
            redisUti.set(uPhone, randomCode, 2 * 60);
            return JsonResult.ok("发送成功");
        }
        else{
                return JsonResult.ok("该用户未注册");
        }
    }
    //验证邮箱验证码是否正确
    @ApiOperation(value = "验证邮箱验证码是否正确")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userEmail", value = "用户邮箱", dataType = "String", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", required = true)
    })
    @PostMapping("/verificationCode")
    public JsonResult verificationCode(String userEmail,String code) {
        if (userEmail == null || code == null){
            return  JsonResult.error(JsonResult.NO);
        }
        if (redisUti.get(userEmail) != null && redisUti.get(userEmail).equals(code)) {
            return JsonResult.ok("验证码正确");
        }else {
            return JsonResult.error("验证码或邮箱不正确");
        }
    }

    //修改密码
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uPhone", value = "用户邮箱", dataType = "String", required = true),
            @ApiImplicitParam(name = "newPassWord", value = "新密码", dataType = "String", required = true)
    })
    @PostMapping("/updatePassword")
    public JsonResult updatePassword(String uPhone,String newPassWord) {
        if (uPhone == null || newPassWord == null){
            return  JsonResult.error(JsonResult.NO);
        }
        Map<String,String> map=new HashMap<>();
        map.put("uPhone",uPhone);
        map.put("uPwd",Md5Salt.md5PlusSalt(newPassWord));
        int i = userService.updatePassword(map);
        if (i>0){
            return JsonResult.ok(JsonResult.UPDATE_SUCCESS);
        }else {
            return JsonResult.error(JsonResult.UPDATE_MISS);
        }
    }

    //添加建议
    @ApiOperation(value = "添加建议")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "fContent", value = "意见内容", dataType = "String", required = true)
    })
    @PostMapping("/createFeedback")
    public JsonResult createFeedback(Integer uId,String fContent) {
        if (uId == null || fContent == null){
            return  JsonResult.error(JsonResult.NO);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("uId",uId);
        map.put("fContent",fContent);
        int feedback = userService.createFeedback(map);
        if (feedback>0){
            return JsonResult.ok(JsonResult.INSERT_SUCCESS);
        }else {
            return JsonResult.error(JsonResult.INSERT_MISS);
        }
    }
}
